package com.app.newiptv.presenter;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;

import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.allchannels.MainChanel;
import com.app.newiptv.bean.allchannels.Program;
import com.app.newiptv.callback.IRequestCallback;
import com.app.newiptv.callback.RequestCallback;
import com.app.newiptv.promote.UserRecodeRunnable;
import com.app.newiptv.service.AHservice;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.CacheDataPresenter;
import com.app.newiptv.utils.Paths;
import com.app.newiptv.utils.SystemTimeDate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Shinelon on 2017/9/15.
 */

public class AllChannelsPresenter {
    private boolean isDisplayed;
    private Callback callback;
    public List<MainChanel> listContent;
    private List<Program> programList;
    private List<Program.Epg> epgList;
    private AllChannelsViewHolder viewHolder;
    private Program currentProgram;
    private int programId;
    private Activity mActivity;
    private AHservice service;

    private Map<String,Program> epgCache;

    private Map<String,Program> programHashMap=new HashMap<>();

    Map<String, List<Program>> channelMap = new HashMap<>();

    public AllChannelsPresenter(Activity mActivity) {
        this.mActivity = mActivity;
        epgCache=CacheDataPresenter.getPresenter(mActivity).getEpgCache();
    }

    public void setDisplayed(boolean displayed) {
        isDisplayed = displayed;
    }

    //加载数据
    public void loadItem(Bundle params, final Callback callback) {
        this.callback = callback;
        service = new AHservice();
        String url = params.getString("url");
        APPLog.printInfo("开始加载频道列表数据");

        List<MainChanel> contents = CacheDataPresenter.getPresenter(mActivity).getListContent();
        if (null != contents && contents.size() > 0) {
            viewHolder.setLineOneView(true);
            listContent = contents;
            callback.onMovieCompleted(AllChannelsPresenter.this, contents.size());
        } else {
            service.channelAllCallback(url, new RequestCallback() {
                @Override
                public void onLoadComplete(String contentID, int pageNumber, int count, List contents) {
                    if (callback == null || !isDisplayed) {
                        APPLog.printInfo("onLoadComplete:callback :");
                        return;
                    }
                    APPLog.printInfo("onLoadComplete:callback :");
                    if (count > 0) {
                        viewHolder.setLineOneView(true);
                        listContent = contents;
                        callback.onMovieCompleted(AllChannelsPresenter.this, count);
                    }
                }

                @Override
                public void onLoading(String contentID) {

                }

                @Override
                public void onFailed(String code, String msg) {

                }
            });
        }
    }

    public void loadChannels(int positon) {
        int id = listContent.get(positon).getId();
        if (id == MyApplication.COLLECTIION) {
            List<Program> programs = CacheDataPresenter.getPresenter(mActivity).loadProgramAll();
            if (callback == null || !isDisplayed) {
                return;
            }
            programList = programs;
            if (programList.size() != 0) {
                viewHolder.setLineTwoView(true);
                callback.onChannelCompleted(AllChannelsPresenter.this, programList.size());
            }
            viewHolder.setmThreeStageRv(false);
        } else {
            //记录用户直播
            UserRecodeRunnable runnable = new UserRecodeRunnable();
            runnable.loadData(Paths.HOSTPATH + Paths.STATE, String.valueOf(id), "live");

            //这里直接获取数据就行了
            List<MainChanel.Lives> lives = listContent.get(positon).getLives();
            List<Program> list = channelMap.get(positon + "");
            if (null == list) {
                list = new ArrayList<>();
                channelMap.put(positon + "", list);
            }else {
                list.clear();
            }
            programList = list;
            for (MainChanel.Lives item : lives) {
                programList.add(new Program(item));
            }

            if (programList.size() != 0) {
                viewHolder.setLineTwoView(true);
                callback.onChannelCompleted(AllChannelsPresenter.this, programList.size());
            }
            viewHolder.setmThreeStageRv(false);
        }
    }

    public Program toPlayPosition(int position) {
        if (programList != null && position <= programList.size()) {
            Program program = programList.get(position);
            return program;
        }
        return null;
    }

    public Bundle toPlayTvodProgram(int position) {
        Bundle bundle = new Bundle();
        String url = currentProgram.getReview();
        if(TextUtils.isEmpty(url))
        {
            return null;
        }
//        url = "http://58.241.83.166:8081/0068/index.m3u8";
        String startTime = epgList.get(position).getStarttime();
        long startLt = new Long(startTime);

        if(System.currentTimeMillis()<startLt*1000)
        {
            return null;
        }

        String endTime = epgList.get(position).getEndtime();
        Program.Epg eng = epgList.get(position);
        //http://192.168.0.39:8081/0001/index.m3u8?begin=0&end=1499003542
        String reviewUrl = url + "?begin=" + startTime + "&end=" + endTime;
        bundle.putString("startTime", startTime);
        bundle.putString("endTime", endTime);
        bundle.putString("reviewUrl", reviewUrl);
        bundle.putSerializable("program", eng);
        bundle.putInt("type", 1003);
        return bundle;
//        String url = currentProgram.getReview();
////        url = "http://58.241.83.166:8081/0068/index.m3u8";
//        String startTime = epgList.get(position).getStarttime();
//        String endTime = epgList.get(position).getEndtime();
//        Program.Epg eng = epgList.get(position);
//        //http://192.168.0.39:8081/0001/index.m3u8?begin=0&end=1499003542
//        String reviewUrl = url + "?begin=" + startTime + "&end=" + endTime;
//        APPLog.printInfo("reviewUrl==>:" + reviewUrl);
//        if (url == null) {
//            Toast.makeText(mActivity, "暂无回看内容", Toast.LENGTH_SHORT).show();
//            return;
//        }
        //if (clickPosition != null) {
        //    clickPosition.lookBackCallback(url, programId, epgList, position);
        //}
//        Intent intent = new Intent();
//        intent.putExtra("type", 1003);
//        intent.putExtra("data", eng);
//        intent.putExtra("playUrl", reviewUrl);
//        intent.setClass(mActivity, PlayerActivity.class);
//        mActivity.startActivity(intent);
    }

    public void loadProgram(int position) {
        programId = programList.get(position).getId();
        service = new AHservice();

        Program program= epgCache.get(programId+"");
         if(null!=program&&null!=program.getEpg())
         {
             epgList=program.getEpg();
             currentProgram=programHashMap.get(programId+"");
             callback.onProgramCompleted(AllChannelsPresenter.this, epgList.size());
             viewHolder.setmThreeStageRv(true);
         }

        service.loadVodItemData(Paths.HOSTPATH + Paths.PROGRAM_LIVE + "/" + programId, new IRequestCallback() {

            @Override
            public void onLoadComplete(String contentID, int pageNumber, int count, Object dto) {
                currentProgram = (Program) dto;
                programHashMap.put(programId+"",currentProgram);
                epgList = ((Program) dto).getEpg();
                if (epgList != null) {
                    epgCache.put(programId+"",currentProgram);
                    callback.onProgramCompleted(AllChannelsPresenter.this, epgList.size());
                }
                viewHolder.setmThreeStageRv(true);
            }

            @Override
            public void onLoading(String contentID) {

            }

            @Override
            public void onFailed(String code, String msg) {

            }
        });
    }

    public void onBindMainChanelView(MainViewHolder holder, int position) {
        if (!isDisplayed) {
            return;
        }
        holder.setmainChanelName(listContent.get(position).getName());
    }

    public void onBindChannel(SencondViewHolder viewHolder, int position) {
        if (isDisplayed) {
            viewHolder.setChannel(programList.get(position).getName());
        }
    }

    public void onBindProgram(ProgramViewHolder viewHolder, int position) {
        if (!isDisplayed) {
            return;
        }
        long time = System.currentTimeMillis();
        viewHolder.setTitleText(epgList.get(position).getTitle());
        viewHolder.setStartTimeText(SystemTimeDate.stampToMMddDate(epgList.get(position).getStarttime()));
        viewHolder.setEndTimeText(SystemTimeDate.stampToHHmmDate(epgList.get(position).getStarttime()) + " - " + SystemTimeDate.stampToHHmmDate(epgList.get(position).getEndtime()));
        long startLt = new Long(epgList.get(position).getStarttime());
        long endLt = new Long(epgList.get(position).getEndtime());
        startLt *= 1000;
        endLt *= 1000;
        if (time >= startLt && time <= endLt) {
            viewHolder.setTypeBtnText("直播", 1);
        } else if (time > endLt) {
            viewHolder.setTypeBtnText("回看", 0);
        } else if (time < startLt) {
            viewHolder.setTypeBtnText("预约", 0);
        }
    }

    public void onBindAllChannels(AllChannelsViewHolder viewHolder) {
        this.viewHolder = viewHolder;

    }

    public interface Callback {
        void onError(int code, String msg);

        void onMovieCompleted(AllChannelsPresenter presenter, int count);

        void onChannelCompleted(AllChannelsPresenter presenter, int count);

        void onProgramCompleted(AllChannelsPresenter presenter, int count);
    }

    public interface MainViewHolder {
        void setmainChanelName(String name);
    }

    public interface SencondViewHolder {
        void setChannel(String name);
    }

    public interface ProgramViewHolder {
        void setTitleText(String name);

        void setTypeBtnText(String name, int type);

        void setStartTimeText(String name);

        void setEndTimeText(String name);

    }

    public interface AllChannelsViewHolder {
        void setmThreeStageRv(boolean isShow);

        void setLineTwoView(boolean isShow);

        void setLineOneView(boolean isShow);
    }
}
